package io.github.maojian.bianrysearch;

import org.junit.Test;

import java.util.Arrays;
import java.util.HashSet;

/**
 * @Auther: jian.mao
 * @Date: 2022-06-30 16:57
 * @Description: https://leetcode.cn/problems/intersection-of-two-arrays-ii/
 */
public class Q350 {
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums2);
        int nums1Length = nums1.length;
        int nums2Length = nums2.length;
        HashSet<Integer> list = new HashSet<>();
        for (int i = 0; i < nums1Length; i++) {
            int target = nums1[i];
            int left = 0, right = nums2Length - 1;
            while (left <= right) {
                int mid = (right - left) / 2 + left;
                if (nums2[mid] == target) {
                    list.add(target);
                    break;
                } else if (nums2[mid] > target) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            }
        }
        return list.stream().mapToInt(Integer::new).toArray();
    }

    @Test
    public void test() {
        int nums1[] = new int[]{4,9,5};
        int nums2[] = new int[]{9,4,9,8,4};
        Arrays.stream(intersect(nums1, nums2)).forEach(System.out::print);
    }
}
